package cn.wawi.common;

import java.beans.PropertyEditorSupport;
import org.apache.commons.lang.StringEscapeUtils;

import cn.wawi.utils.StringEscapeUtil;

/**
 * 
 * @description 与spring mvc的@InitBinder结合 用于防止XSS攻击
 * @author gongliang
 * @date 2015年3月29日 下午4:24:51
 */
public class StringEscapeEditor extends PropertyEditorSupport {

	private boolean escapeHTML;// 编码HTML
	private boolean escapeJavaScript;// 编码javascript
	private boolean escapeSQL;       //sql注入

	public StringEscapeEditor() {
		super();
	}

	public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript,boolean escapeSQL) {
		super();
		this.escapeHTML = escapeHTML;
		this.escapeJavaScript = escapeJavaScript;
		this.escapeSQL = escapeSQL;
	}

	@Override
	public String getAsText() {
		Object value = getValue();
		return value != null ? value.toString() : "";
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (text == null) {
			setValue(null);
		} else {
			String value = text;
			if (escapeHTML) {
				value =StringEscapeUtil.escapeHtml4(value);
			}
			if (escapeJavaScript) {
				value = StringEscapeUtils.escapeJavaScript(value);
			}
			if (escapeSQL) { 
				value = StringEscapeUtils.escapeSql(value); 
			}    
			setValue(value);
		}
	}
}
